package tk.mybatis.web.service.impl;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.web.mapper.DictMapper;
import tk.mybatis.web.model.SysDict;
import tk.mybatis.web.service.DictService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuzh
 */
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public SysDict findById(Long id) {
        return dictMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SysDict> selectByPage(Map<String, Object> params) {
        return dictMapper.selectByPage(params);
    }

    @Override
    public boolean saveOrUpdate(SysDict sysDict) {
        if(sysDict.getId() == null){
            return dictMapper.insert(sysDict) == 1;
        } else {
            return dictMapper.updateById(sysDict) == 1;
        }
    }

    @Override
    public boolean deleteById(Long id) {
    	if(id == null){
    		throw new NullPointerException("id");
    	}
        return dictMapper.deleteById(id) == 1;
    }

    @Override
    public List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit) {
        RowBounds rowBounds = RowBounds.DEFAULT;
        if(offset != null && limit != null){
            rowBounds = new RowBounds(offset, limit);
        }
        return dictMapper.selectBySysDict(sysDict, rowBounds);
    }

    /**
     * 通过subList方法，获取到两索引间的所有数据
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public List<SysDict> selectDictsByArray(int pageNo, int pageSize) {
        List<SysDict> dicts = dictMapper.selectDictsByArray();
        //从第几条数据开始
        int firstIndex = (pageNo - 1) * pageSize;
        //到第几条数据结束
        int lastIndex = pageNo * pageSize;
        return dicts.subList(firstIndex, lastIndex);
    }

    /**
     * 在sql语句后面添加limit实现分页
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public List<SysDict> selectDictsBySql(int pageNo, int pageSize) {
        Map<String, Object> data = new HashMap<String, Object>(3);
        data.put("currIndex", (pageNo-1)*pageSize);
        data.put("pageSize", pageSize);
        return dictMapper.selectDictsBySql(data);
    }

    /**
     * 通过RowBounds参数进行分页
     * @param start
     * @param limit
     * @return
     */
    @Override
    public List<SysDict> selectDictsByRowBounds(int start, int limit) {
        return dictMapper.selectDictsByRowBounds(new RowBounds(start, limit));
    }
}
